<template>
	<section>
		<!--工具条-->
		<el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
			<el-form :inline="true" :model="filters">
				<el-form-item>
					<el-input v-model="filters.couponsName" clearable placeholder="优惠券名称"></el-input>
				</el-form-item>		
				<el-form-item>
					<el-button type="primary" size="medium" v-on:click="handleCurrentChange(1)">查询</el-button>
				</el-form-item>
				<el-form-item class="fr">
					<el-button type="primary" size="medium" plain @click="handleAdd">新增</el-button>
				</el-form-item>
			</el-form>
		</el-col>

		<!--列表-->
		<el-table :data="list" stripe highlight-current-row v-loading="listLoading" border @selection-change="selsChange" style="width: 100%;">
			<el-table-column prop="id" label="ID" min-width="40" align="center">
			</el-table-column>
			<el-table-column prop="couponsName" label="优惠券名称" min-width="60" align="center">
			</el-table-column>
			<el-table-column prop="minUseMoney" label="需满金额" min-width="60" align="center">
			</el-table-column>
			<el-table-column prop="money" label="优惠金额" min-width="60" align="center">
			</el-table-column>
			<el-table-column prop="days" label="有效期(天)" min-width="60" align="center">
			</el-table-column>
			<el-table-column prop="addTime" label="创建时间" :formatter="formatDate" min-width="100" align="center">
			</el-table-column>
			<el-table-column label="操作" align="center" width="280">
				<template slot-scope="scope">
					<el-button size="mini"  type="success" plain @click="handleAll(scope.row.id)">派发所有用户</el-button>
					<el-button size="mini"  type="success" plain @click="handleZengsong(scope.row.id)">派发指定用户</el-button>
					<!--<el-popover placement="right" trigger="click">
						<el-button size="mini"  type="success" plain @click="handleAll(scope.row.id)">派发所有用户</el-button>
						<el-button size="mini"  type="success" plain @click="handleZengsong(scope.row.id)">派发指定用户</el-button>
						<el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
					    <el-button type="danger" plain size="mini" @click="handleDel(scope.row.id)">删除</el-button>
	        		    <el-button size="mini" plain type="primary" slot="reference">更多</el-button>
	        	    </el-popover>-->
					
				</template>
			</el-table-column>
		</el-table>

		<!--工具条-->
		<el-col :span="24" class="toolbar">
			<el-pagination layout="prev, pager, next, jumper" @current-change="handleCurrentChange" :page-size="pageSize" :total="total" style="float:right;">
			</el-pagination>
		</el-col>
		<!--新增界面-->
		<el-dialog title="新增" :visible.sync="addFormVisible" :close-on-click-modal="false" @close="dialogClose" width="700px">
            <el-form :model="addForm" label-width="120px" ref="addForm">
            	<el-form-item label="优惠券名称" prop="couponsName">
					<el-input v-model="addForm.couponsName" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="需满金额" prop="minUseMoney">
					<el-input v-model="addForm.minUseMoney" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="优惠金额" prop="money">
					<el-input v-model="addForm.money" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="有效期" prop="days">
					<el-input v-model="addForm.days" auto-complete="off">
						<template slot="append">天</template>
					</el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button size="mini" @click.native="addFormVisible = false">取消</el-button>
				<el-button size="mini" type="primary" @click.native="addSubmit">提交</el-button>
			</div>
		</el-dialog>
		<!--编辑界面-->
		<el-dialog title="修改" :visible.sync="editFormVisible" :close-on-click-modal="false" @close="dialogClose" width="700px">
            <el-form :model="editForm" label-width="120px" ref="editForm">
            	<el-form-item label="优惠券名称" prop="couponsName">
					<el-input v-model="editForm.couponsName" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="需满金额" prop="minUseMoney">
					<el-input v-model="editForm.minUseMoney" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="优惠金额" prop="money">
					<el-input v-model="editForm.money" auto-complete="off"></el-input>
				</el-form-item>
				<el-form-item label="有效期" prop="days">
					<el-input v-model="editForm.days" auto-complete="off">
						<template slot="append">天</template>
					</el-input>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button size="mini" @click.native="editFormVisible = false">取消</el-button>
				<el-button size="mini" type="primary" @click.native="editSubmit">提交</el-button>
			</div>
		</el-dialog>
		<!--派发界面-->
		<el-dialog title="赠送课程" :visible.sync="zengFormVisible" :close-on-click-modal="false" width="500px" style="margin-top: -80px;"> 
			<el-form :model="zengForm" label-width="110px"  ref="zengForm">
				<el-form-item label="用户手机号码" prop="userIds" :rules="[{ required: true, message: '请选择用户', trigger: 'blur' }]">
                    <el-select v-model="zengForm.userIds" filterable remote reserve-keyword placeholder="请输入用户手机号码" :remote-method="remoteMethod">
                        <el-option v-for="item in userList" :key="item.id" :label="item.label" :value="item.id"></el-option>
                    </el-select>
				</el-form-item>
			</el-form>
			<div slot="footer" class="dialog-footer">
				<el-button size="mini" @click.native="zengFormVisible = false">取消</el-button>
				<el-button size="mini" type="primary" @click.native="zengSubmit">确定</el-button>
			</div>
		</el-dialog>
	</section>
</template>

<script>
	export default {
		data() {
			return {
				filters: {
                    couponsName:'',
				},
				list: [],
				total: 0,
				page: 1,
				pageSize: 10,
				listLoading: false,
				sels: [],
				addFormVisible: false,
				addLoading: false,
				addForm: {
					minUseMoney: '',
					money: '',
					days:'',
					couponsName:'',
                },
                editFormVisible: false,
				editLoading: false,
				editForm: {
					id: '',
					minUseMoney: '',
					money: '',
					days:'',
					couponsName:'',
                },
                userList:[],
                zengLoading:false,
		        zengFormVisible:false,
		        zengForm:{
		      	    id:'',
		      	    userIds:'',
		        },
			}
		},
		methods: {
			selsChange: function (sels) {
				this.sels = sels;
			},
			
			//时间转换开始时间 
			formatDate(row, column) {
                let date = new Date(parseInt(row.addTime));
                let Y = date.getFullYear() + '-';
                let M = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) + '-' : date.getMonth() + 1 + '-';
                let D = date.getDate() < 10 ? '0' + date.getDate() + ' ' : date.getDate() + ' ';
                let h = date.getHours() < 10 ? '0' + date.getHours() + ':' : date.getHours() + ':';
                let m = date.getMinutes()  < 10 ? '0' + date.getMinutes() + ':' : date.getMinutes() + ':';
                let s = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
                return Y + M + D + h + m + s;
            },
            zeroize(num) {
                return (String(num).length == 1 ? "0" : "") + num;
            },
            timestampFormat(timestamp) {
                var curTimestamp = parseInt(new Date().getTime() / 1000); //当前时间戳
                var timestampDiff = curTimestamp - parseInt(timestamp / 1000); // 参数时间戳与当前时间戳相差秒数
                var curDate = new Date(curTimestamp * 1000); // 当前时间日期对象
                var tmDate = new Date(parseInt(timestamp / 1000) * 1000); // 参数时间戳转换成的日期对象
                var Y = tmDate.getFullYear(),
                m = tmDate.getMonth() + 1,
                d = tmDate.getDate();
                var H = tmDate.getHours(),
                i = tmDate.getMinutes(),
                s = tmDate.getSeconds();
                return (Y + "-" + this.zeroize(m) + "-" + this.zeroize(d) + " " + this.zeroize(H) + ":" + this.zeroize(i));
            },
			handleCurrentChange(val) {
				this.page = val;
				this.getUsers();
			},
			//获取列表
			getUsers:function (){
				this.listLoading = true;
				let para = {
					page: this.page,
					size: this.pageSize,
                    couponsName: this.filters.couponsName,
				};
				var instance = this.$http.create({headers: {'content-type': 'application/x-www-form-urlencoded','admin_five_palace_token':JSON.parse(sessionStorage.getItem('token'))},
				});  
				instance.post('admin/coupon/couponsList/v1_0_0', this.qs.stringify(para)).then(data => {
					let  res = data.data;
					if (res.code !== 0) {
						this.$message({
							message: res.msg,
							type: 'error'
						});
					} else {
						this.total = res.total;
						this.list = res.rows;
						this.listLoading = false;
					}
				});
			},
			//显示新增界面
			handleAdd: function () {
				this.addFormVisible = true;
				this.addForm = {
					couponsName: '',
					money: '',
					days:'',
					name:'',
				};
			},
			//新增
			addSubmit: function () {
				this.$refs.addForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认新增吗？', '提示', {}).then(() => {
                            this.addLoading = true;
                            let para = {
                            	minUseMoney: this.addForm.minUseMoney,
                            	money: this.addForm.money,
                            	days: this.addForm.days,
                            	couponsName: this.addForm.couponsName,
                            };
                            var instance = this.$http.create({headers: {'content-type': 'application/x-www-form-urlencoded','admin_five_palace_token':JSON.parse(sessionStorage.getItem('token'))},
							});  
							instance.post('admin/coupon/addCoupons', this.qs.stringify(para)).then(data => {
								
								let  res = data.data;
								if (res.code !== 0) {
									this.$message({
										message: res.msg,
										type: 'error'
									});
								} else {
									this.$message({
										message: '成功',
										type: 'success'
                                   });
									this.$refs['addForm'].resetFields();
									this.addFormVisible = false;
									this.getUsers();
								}
								this.addLoading = false;
							});
						});
					}
				});
			},
            //显示编辑界面
			handleEdit: function (index,row) {
				this.editFormVisible = true;
				console.log(row,121);
				this.editForm.id = row.id;
				this.editForm.minUseMoney = row.minUseMoney;
				this.editForm.money = row.money;
				this.editForm.couponsName = row.couponsName;
				this.editForm.days = row.days;
				
			},
			//新增
			editSubmit: function () {
				this.$refs.editForm.validate((valid) => {
					if (valid) {
						this.$confirm('确认修改吗？', '提示', {}).then(() => {
                            this.editLoading = true;
                            let para = {
                            	id:this.editForm.id,
                            	minUseMoney: this.editForm.minUseMoney,
                            	money: this.editForm.money,
                            	days: this.editForm.days,
                            	couponsName: this.editForm.couponsName,
                            };
                            var instance = this.$http.create({headers: {'content-type': 'application/x-www-form-urlencoded','admin_five_palace_token':JSON.parse(sessionStorage.getItem('token'))},
							});  
							instance.post('sys/api/platform/manage/updCoupons/v1_0_0', this.qs.stringify(para)).then(data => {
								
								let  res = data.data;
								if (res.code !== 0) {
									this.$message({
										message: res.msg,
										type: 'error'
									});
								} else {
									this.$message({
										message: '成功',
										type: 'success'
                                   });
									this.$refs['editForm'].resetFields();
									this.editFormVisible = false;
									this.getUsers();
								}
								this.editLoading = false;
							});
						});
					}
				});
			},
			dialogClose(){},
			selsChange: function (sels) {
				this.sels = sels;
			},
			//删除
			handleDel(id) {
				this.$confirm('确认删除吗？', '提示', {}).then(() => {
					this.listLoading = true;
					var instance = this.$http.create({headers: {'content-type': 'application/x-www-form-urlencoded','admin_five_palace_token':JSON.parse(sessionStorage.getItem('token'))},
					});  
					instance.post('sys/api/platform/manage/deleteCoupons/v1_0_0', this.qs.stringify({id: id})).then(data => {
						
						let  res = data.data;
						if (res.code !== 0) {
							this.$message({
								message: res.msg,
								type: 'error'
							});
						} else {
							this.$message({
								message: '成功',
								type: 'success'
							});
							this.getUsers();
						}
					})
				}).catch(() => {

				});
			},
			//批量删除
			batchRemove: function () {
				var ids = this.sels.map(item => item.id).toString();
				this.handleDel(ids);
			},
			//派发所有用户
			handleAll(id) {
				this.$confirm('确认派发给所有用户吗？', '提示', {}).then(() => {
					this.listLoading = true;
					var instance = this.$http.create({headers: {'content-type': 'application/x-www-form-urlencoded','admin_five_palace_token':JSON.parse(sessionStorage.getItem('token'))},
					});  
					instance.post('admin/coupon/payoutCouponsAll', this.qs.stringify({id: id})).then(data => {
						
						let  res = data.data;
						if (res.code !== 0) {
							this.$message({
								message: res.msg,
								type: 'error'
							});
						} else {
							this.$message({
								message: '成功',
								type: 'success'
							});
							this.getUsers();
						}
					})
				}).catch(() => {

				});
			},
			//派发优惠券
			handleZengsong(id){
				this.zengFormVisible = true
				this.zengForm.id = id
			},
			//派发
			zengSubmit: function () {
				this.$refs.zengForm.validate((valid) => {
					if (valid) {
						this.$confirm('确定派发吗?', '提示', {}).then(() => {
							this.editLoading = true;
							let para = {
								id:this.zengForm.id,
				            	userId:this.zengForm.userIds,
							}
							var instance = this.$http.create({headers: {'content-type': 'application/x-www-form-urlencoded','admin_five_palace_token':JSON.parse(sessionStorage.getItem('token'))},
							});  
							instance.post('admin/coupon/payoutCouponsSingle', this.qs.stringify(para)).then(data => {
								
								let  res = data.data;
								if (res.code !== 0) {
									this.$message({
										message: res.msg,
										type: 'error'
									});
								} else {
									this.zengLoading = false;
									this.$message({
										message: '成功',
										type: 'success'
									});
									this.$refs['zengForm'].resetFields();
									this.zengFormVisible = false;
								}
							});
						});
					}
				});
			},
			remoteMethod(query){
				if (query !== '') {
		          setTimeout(() => {
		            this.getUserList(query)
		          }, 200);
		        } else {
		          this.userList = [];
		        }
			},
			getUserList(query){
				let para = {
					phone: query,
				};
				var instance = this.$http.create({headers: {'content-type': 'application/x-www-form-urlencoded','admin_five_palace_token':JSON.parse(sessionStorage.getItem('token'))},
				});  
				instance.post('admin/common/getUserSelectEntity', this.qs.stringify(para)).then(data => {
					let  res = data.data;
					this.userList = res;
				}); 
			}
		},
		mounted() {
			this.getUsers();
		}
	}

</script>